// 用户认证工具

// Token存储key
const TOKEN_KEY = 'access_token';
const USER_INFO_KEY = 'user_info';

// 获取token
const getToken = () => {
  return uni.getStorageSync(TOKEN_KEY);
};

// 设置token
const setToken = (token) => {
  uni.setStorageSync(TOKEN_KEY, token);
};

// 移除token
const removeToken = () => {
  uni.removeStorageSync(TOKEN_KEY);
};

// 获取用户信息
const getUserInfo = () => {
  const userInfo = uni.getStorageSync(USER_INFO_KEY);
  return userInfo ? userInfo : null;
};

// 设置用户信息
const setUserInfo = (userInfo) => {
  uni.setStorageSync(USER_INFO_KEY, userInfo);
};

// 移除用户信息
const removeUserInfo = () => {
  uni.removeStorageSync(USER_INFO_KEY);
};

// 检查是否已登录
const isLoggedIn = () => {
  const token = getToken();
  const userInfo = getUserInfo();
  return !!(token && userInfo);
};

// 清除所有登录信息
const clearAuth = () => {
  removeToken();
  removeUserInfo();
};

// 登录成功后保存信息
const saveAuthInfo = (tokenData, userInfo) => {
  setToken(tokenData.access_token);
  setUserInfo(userInfo);
};

// 退出登录
const logout = () => {
  clearAuth();
  uni.reLaunch({
    url: '/pages/login/login'
  });
};

// 检查登录状态，如果未登录则跳转到登录页
const checkAuth = () => {
  if (!isLoggedIn()) {
    uni.reLaunch({
      url: '/pages/login/login'
    });
    return false;
  }
  return true;
};

// 导出所有方法
export {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo,
  isLoggedIn,
  clearAuth,
  saveAuthInfo,
  logout,
  checkAuth
};

